package com.rp.system.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.rp.common.utils.JsonUtil;
import com.rp.common.utils.RpUtil;
import com.rp.controller.RpController;
import com.rp.system.po.Preferences;
import com.rp.system.service.PreferencesService;

@Controller
@RequestMapping("/rp/system/baseData/preMng/")
public class PreferencesController extends RpController {
	
	@Autowired
	private PreferencesService preferencesService;
	
	/**
	 * 主界面列表数据获取
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getPreferences")
	public List<Preferences> getPreferences(){
		List<Preferences> pres = 
				preferencesService.getPreferencesDao()
				.find("from Preferences order by createDate desc");
		return pres;
	}
	
	@ResponseBody
	@RequestMapping("addPreferences")
	public String addPreferences(String json){
		try{
			
			Map<String, Object> obj = JsonUtil.jsonToMap(json);
			Preferences pre = new Preferences();
			pre.setPreName((String)obj.get("preName"));
			pre.setPreValue((String)obj.get("preValue"));
			pre.setRemark((String)obj.get("remark"));
			
			preferencesService.addPreferences(pre);
			
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}
	
	@ResponseBody
	@RequestMapping("savePreferences")
	public String savePreferences(String data){
		try {
			List<Preferences> pres = JsonUtil.jsonToList(data, "com.rp.system.po.Preferences");
			for (Preferences pre : pres) {
				if(pre.getId() == null){
					preferencesService.addPreferences(pre);
				}else{
					preferencesService.updatePreferences(pre);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("deletePreferences")
	public String deletePreferences(String data){
		try {
			List<Preferences> pres = JsonUtil.getMapper().readValue(data, JsonUtil.getCollectionType(ArrayList.class, Preferences.class));
			for (Preferences pre : pres) {
				preferencesService.deletePreferences(pre.getId());
			}
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("getPreValue")
	public String getPreValue(@RequestParam(required=true) String preName){
		String hql = "from Preferences where preName = ?";
		List<Preferences> pres = preferencesService.getPreferencesDao()
				.find(hql, preName);
		if(pres.size() > 0){
			Preferences pre = pres.get(0);
			return pre.getPreValue();
		}else{
			return "null";
		}
	}
	
	@ResponseBody
	@RequestMapping("setPreValue")
	public String setPreValue(String preName, String preValue){
		//preValue = preValue.replace("<", "&lt;").replace(">", "&gt;");
		preValue = preValue.replace("script", " ");
		String hql = "from Preferences where preName = ?";
		List<Preferences> pres = preferencesService.getPreferencesDao()
				.find(hql, preName);
		if(pres.size() > 0){
			Preferences pre = pres.get(0);
			pre.setPreValue(preValue);
			preferencesService.updatePreferences(pre);
		}else{
			return "保存失败，失败原因：没有查到对应名称的参数。";
		}
		
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("getAllPreValue")
	public List<Preferences> getAllPreValue(){
		String hql = "from Preferences";
		List<Preferences> pres = preferencesService.getPreferencesDao().find(hql);
		return pres;
	}
	
	
	/**
	 * 通过文件导入参数（暂时不用）
	 * @param file
	 * @return
	 */
	//@RequestMapping("importPre")
	public ModelAndView importPre(@RequestParam MultipartFile file){
		String saveDirectory = this.getWebServerDirectory()+"/importDirectory/";
		String fileName = file.getOriginalFilename();
		File targetFile = new File(saveDirectory, fileName);
		//如果目录不存在则创建目录
        if(!targetFile.exists()){  
            targetFile.mkdirs();
        }
        //保存文件至服务器中
        try {  
            file.transferTo(targetFile);
            String fileContext = RpUtil.readFileContent(saveDirectory+fileName);
            //System.out.println(fileContext);
            List<Preferences> pres = JsonUtil.getMapper().readValue(fileContext, JsonUtil.getCollectionType(ArrayList.class, Preferences.class));
			for (Preferences pre : pres) {
				//首先先查找数据库中是否存在相同参数名称的参数
				List<Preferences> dbPres = 
						preferencesService.getPreferencesDao()
						.find("from Preferences where preName = ?", pre.getPreName());
				//如果存在相同名称的参数
				if(dbPres.size() > 0){
					Preferences dbPre = preferencesService.getPreferencesDao().get(pre.getId());
					dbPre.setPreValue(pre.getPreValue());
					dbPre.setRemark(pre.getRemark());
					preferencesService.updatePreferences(dbPre);
				}else{
					Preferences newPre = new Preferences();
					newPre.setPreName(pre.getPreName());
					newPre.setPreValue(pre.getPreValue());
					newPre.setRemark(pre.getRemark());
					preferencesService.addPreferences(newPre);
				}
			}
        } catch (Exception e) {  
            e.printStackTrace();
            model.put("errorMsg", "参数导入失败！请重新操作...");
            return forward("/rp/common/error.jsp");
        } finally {
        	targetFile.delete();
        }
		
		return forward("");
	}
	
	@ResponseBody
	@RequestMapping("importPre")
	public String importPre(String json){
		try{
			List<Preferences> pres = JsonUtil.getMapper().readValue(json, JsonUtil.getCollectionType(ArrayList.class, Preferences.class));
			for (Preferences pre : pres) {
				//首先先查找数据库中是否存在相同参数名称的参数
				List<Preferences> dbPres = 
						preferencesService.getPreferencesDao()
						.find("from Preferences where preName = ?", pre.getPreName());
				//如果存在相同名称的参数
				if(dbPres.size() > 0){
					Preferences dbPre = preferencesService.getPreferencesDao().get(pre.getId());
					dbPre.setPreValue(pre.getPreValue());
					dbPre.setRemark(pre.getRemark());
					preferencesService.updatePreferences(dbPre);
				}else{
					Preferences newPre = new Preferences();
					newPre.setPreName(pre.getPreName());
					newPre.setPreValue(pre.getPreValue());
					newPre.setRemark(pre.getRemark());
					preferencesService.addPreferences(newPre);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		return SUCCESS;
	}
	
}
